package com.cy.dda.service.rule.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.cy.dda.comm.constant.CacheConstants;
import com.cy.dda.dao.mapper.rule.RoleMapper;
import com.cy.dda.model.PageBean;
import com.cy.dda.model.domain.rule.Role;
import com.cy.dda.model.query.rule.RoleListAdminQuery;
import com.cy.dda.service.BaseService;
import com.cy.dda.service.rule.RoleService;

/**
 * 角色管理
 *
 * @author: tanyilin
 * @create: 2018年11月9日 上午10:16:53
 */
@Service
public class RoleServiceImpl extends BaseService implements RoleService {

	@Autowired
	private RoleMapper roleMapper;
	
	@Override
	public PageBean<Role> selectRoleListAdmin(RoleListAdminQuery query) {
		Role role = new Role();
		role.setName(query.getName());
		int total = roleMapper.selectCount(role);
		List<Role> list = new ArrayList<>();
		if(total > 0) {
			query.startPage();
			list = roleMapper.select(role);
		}
		return new PageBean<>(list, total);
	}

	@Override
	@Cacheable(value = CacheConstants.CACHE_RULE_ROLE)
	public List<Role> allRolesInCache() {
		List<Role> list = roleMapper.selectAll();
		list.stream().forEach(r -> {
			r.setCreateTime(null);
			r.setUpdateTime(null);
			r.setRemarks(null);
		});
		return list;
	}

	@Override
    @Transactional
	@CacheEvict(value = CacheConstants.CACHE_RULE_ROLE, allEntries = true, beforeInvocation = true)
	public void addRole(Role role) {
		Date time = new Date();
		role.setCreateTime(time);
		role.setUpdateTime(time);
        roleMapper.insertSelective(role);
	}

	@Override
	@Transactional
	@CacheEvict(value = CacheConstants.CACHE_RULE_ROLE, allEntries = true, beforeInvocation = true)
	public void updateRole(Role role) {
		role.setUpdateTime(new Date());
        roleMapper.updateByPrimaryKeySelective(role);
	}

}
